package com.example.xutilsdemo.app

import android.app.Application
import com.blankj.utilcode.util.LogUtils
import com.example.xutilsdemo.db.ListDevicesConverter
import com.example.xutilsdemo.db.ListDevices
import com.example.xutilsdemo.db.UserInfoDataBaseBean
import com.example.xutilsdemo.utils.FireGsonUtil
import org.xutils.DbManager
import org.xutils.DbManager.DaoConfig
import org.xutils.db.converter.ColumnConverterFactory
import org.xutils.db.table.TableEntity
import org.xutils.ex.DbException
import org.xutils.x

/**
 *@author: njb
 *@date:  2023/5/24 22:57
 *@desc:
 */
open class MyApp : Application() {
    private lateinit var dbManager: DbManager

    override fun onCreate() {
        super.onCreate()
        instance = this
        initXUtils()
    }

    private fun initXUtils() {
        x.Ext.init(this)
        x.Ext.setDebug(true)
        ColumnConverterFactory.registerColumnConverter(ListDevices::class.java,  ListDevicesConverter())
    }


    companion object {
        lateinit var instance: MyApp
    }


    /**
     * 获取数据库配置信息
     *
     * @return 配置信息对象
     */
    open fun getLocalDbManager(): DbManager {
        val dbConfig = DaoConfig()
            .setDbName("userinfo.db")
            .setDbVersion(2)
            .setDbOpenListener { db: DbManager -> db.database.enableWriteAheadLogging() } //监听数据库打开
            .setDbUpgradeListener { db: DbManager, oldVersion: Int, newVersion: Int ->  //监听数据库更新
                //todo：数据库升级需要做的一些操作
                try {
                    if (newVersion > oldVersion) {
                        db.addColumn(UserInfoDataBaseBean::class.java, "devices")
                        val userList: List<UserInfoDataBaseBean> =
                            db.findAll(UserInfoDataBaseBean::class.java)
                        db.saveOrUpdate(userList)
                        LogUtils.d("--数据库版本升级成功--", FireGsonUtil.listToJson(userList))
                    }
                } catch (e: DbException) {
                    e.printStackTrace()
                }
            }.setTableCreateListener { db: DbManager?, table: TableEntity<*>? -> }
        dbManager = x.getDb(dbConfig)
        return dbManager
    }
}